
#import "Controller.h"
#import "Process.h"

static id movieList;

void fromPlayer(int fd, void *data)
{
	char buf[1024];
	int size;
	
	size = read(fd,buf, sizeof(buf) -1);
	if(size <=0) {/* process dead or done */
		[[movieList removeObject:(id)data] free];
		return;
	}
	
	buf[size] = '\000';
	return;
	
}

@implementation Controller

- open:sender
{
	const char *const *files;
	id openPanel;  
	char fullName[MAXPATHLEN+1];

	char *fileTypes[5] = {"mpeg", "MPEG", "mpg", "MPG", 0};
 
	openPanel = 
  	[[[OpenPanel new] allowMultipleFiles:YES] setTitle:"Open MPEG stream"];

	/* run the open panel */
	if ([openPanel runModalForTypes:fileTypes]){
    	for (files = [openPanel filenames]; files && *files; files++) {	
      		sprintf(fullName,"%s/%s",[openPanel directory],*files);
			if (![self  launchMovie:fullName]) {
        		NXRunAlertPanel("Open","Can't open %s",
				 "Okay", NULL, NULL, *files);
			}
		}
	}
	return self;
}


- (BOOL) launchMovie:(const char *)fullName
{
	char *argv[3] = {0,0,0};
	id proc;
	
	argv[0] = malloc(strlen(playProgram)+1);	
	strcpy(argv[0], playProgram);
	
	argv[1] = malloc(strlen(fullName)+1);
	strcpy(argv[1], fullName);
	
	proc = [ [Process alloc] initFromCommand:argv];
	
	if(!proc) return NO;

	[movies addObject:proc];

	[proc dpsWatchFD:fromPlayer data:proc priority:NX_BASETHRESHOLD];
		
	free(argv[0]);
	free(argv[1]);
	
	return YES;
}



@end

@implementation Controller(ApplicationDelegate)

- (int)app:sender openFile:(const char *)path type:(const char *)type
{
	/* user opens a document from the Workspace Manager. */

	char *fileTypes[4] = {"mpeg", "MPEG", "mpg", "MPG"};
	int i;

	for(i=0;i<4;i++) {	
		if(strcmp(type,fileTypes[i]) == 0) break;
		if(i == 3) return NO;
	}

	if (![self launchMovie:path]) {
		NXRunAlertPanel("Open","Can't open %s", "Okay", NULL, NULL, path);
		return NO;		
	}
	
	return YES;
}

- (BOOL)appAcceptsAnotherFile:sender
/*
 * Inform the workspace that we can open multiple files.
 */
{
  return YES;
}

-appWillInit:sender
{
     strcpy(playProgram, [[NXBundle mainBundle] directory]);
	 strcat(playProgram, "/mpeg_play");
	 
	 if(access(playProgram,X_OK)){
        NXRunAlertPanel("MPlay.app","Can't open mpeg_play",
			"Okay", NULL, NULL, NULL);

		return [sender free];
	 }
 
	movies = [[List alloc] init];
	movieList = movies;
	return self;
}

- appWillTerminate:sender
{
	if(movies) [movies freeObjects];
	
	return self;
}


@end
